<?php
/**
 * Created by PhpStorm.
 * User: chichao
 * Date: 2016/12/22
 * Time: 12:31
 */

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis as Redis;
use App\Users;
use QCloud\Cos\Api;
use Illuminate\Support\Facades\Log;

function postData()
{
    $receipt = $_REQUEST;
    if($receipt==null){
        $receipt = file_get_contents("php://input");
        if($receipt == null){
            $receipt = $GLOBALS['HTTP_RAW_POST_DATA'];
        }
    }
    return $receipt;
}


/**
 * XML格式转Array
 * @param $xml
 * @return bool|mixed
 */
function xml2Array($xml)
{
    if(!$xml){
        return false;
    }
    libxml_disable_entity_loader(true);
    $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $data;
}

/**
 * 打印error级别的日志
 * @param string $message 要打印的日志
 */
function errorLog($message = '')
{
    $type = gettype($message);
    if ($type === 'object'){
        $message = objectToArray($message);
        $message['notice'] = '注意：该数组为对象转化成的';
    }
    Log::error($message);
}

/**
 * 将对象转化为数组
 * @param $array 传入的对象
 * @return array 返回数组
 */
function objectToArray($array)
{
    if(is_object($array)) {
        $array = (array)$array;
    } if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = objectToArray($value);
        }
    }
    return $array;
}

/**
 *把纬度和经度拼接成经纬度字符串
 * @param $lat 纬度
 * @param $lng 经度
 * @return string 经纬度拼接的字符串
 */
function latlng($lat, $lng)
{
    return $lng.','.$lat;
}

/**
 * 计算A和B两个点之间的距离
 * @param $lat1 A点纬度
 * @param $lng1 A点经度
 * @param $lat2 B点纬度
 * @param $lng2 B点经度
 * @param bool $miles 是否以千米为单位
 * @return float 两点间的距离
 */
function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
{
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;
    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlng = $lng2 - $lng1;
    $a = sin($dlat/2)*sin($dlat/2)+cos($lat1)*cos($lat2)*sin($dlng/2)*sin($dlng/2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;
    $dis = ($miles ? ($km * 0.621371192) : $km);
    return round($dis,1);
}

/**
 * 将标签字符串转化为标签数组
 * @param $tag_str 标签字符串
 * @return array 标签数组
 */
function strToTag($tag_str)
{
    return explode(',', $tag_str);
}

/**
 * 给图片修改名称
 * @param $img_name 图片名称
 * @return string 修改后的图片名称
 */
function changeImgName($img_name)
{
    return substr($img_name, 0, 26) . "pictj" . substr($img_name, 31);
}

/**
 * 图片排版
 * @param $photos 图片数组
 * @param bool $continue 是否是每一行图片的结尾，如果是false则停止排版
 */
function layout($photos, $continue = true)
{
    if($continue)
    {
        if($photos->count()==3||$photos->count()==4)
        {
            $sliceNum = rand(1,3);

            layout($photos->slice(0, $sliceNum), 0);
            layout($photos->slice($sliceNum), 0);
        }
        else if($photos->count()==5)
        {
            $sliceNum = rand(2,3);
            layout($photos->slice(0, $sliceNum), 0);
            layout($photos->slice($sliceNum), 0);
        }
        else if($photos->count()==6)
        {
            layout($photos->slice(0, 3), 0);
            layout($photos->slice(3), 0);
        }
        else
        {
            $rowWidth = 0;
            foreach ($photos as $photo) {
                $rowWidth += $photo->ratio;
            }

            $i = 0;
            foreach ($photos as $photo) {               //处理细节
                $photo->rowRatio = $photo->ratio/$rowWidth;
                $photo->cols = $photos->count();
                if($photos->count()==1)         //首次分割1个，则一共就一个，长宽比高度
                    $photo->colRatio = 3/$photo->ratio;
                if($photos->count()==2)
                    $photo->colRatio = 1.7;
                if($photos->count()==3)
                    $photo->colRatio = 1;

                $i++;
                if ( $i == $photos->count() ) {
                    $photo->last = 0;
                }
                else
                    $photo->last = 2;
            }
        }
    }
    else
    {
        $rowWidth = 0;
        foreach ($photos as $photo) {
            $rowWidth += $photo->ratio;
        }

        $i = 0;
        foreach ($photos as $photo) {                   //处理细节
            $photo->rowRatio = $photo->ratio/$rowWidth;
            $photo->cols = $photos->count();

            if($photos->count()==1)
                $photo->colRatio = 1.3;
            if($photos->count()==2)
                $photo->colRatio = 1.2;
            if($photos->count()==3)
                $photo->colRatio = 1;

            $i++;
            if ( $i == $photos->count() ) {
                $photo->last = 0;
            }
            else
                $photo->last = 2;
        }
    }

}

/**
 * 下载图片
 * @param $url 图片网络路径
 * @param string $path 保存本地路径
 */
function downloadImage($url, $data = [], $path = '/temp/')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if (!empty($data)){
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);

    $filename = date('Y-m-d-H-i-s'). '-' .uniqid().".jpg";;
    $resource = fopen($path . $filename, 'a');
    fwrite($resource, $file);
    fclose($resource);
    return $path.$filename;
}

/**
 * 上传图片
 * @param $url 图片服务地本地地址
 * @param string $path 云存储基地址
 * @return string 返回图片在云存储链接
 */
function uploadImage($url, $path = "")
{
    $extension = empty(pathinfo($url, PATHINFO_EXTENSION)) ? 'jpg' : pathinfo($url, PATHINFO_EXTENSION);
    $bucket = 'onecafe';
    $config = array(
        'app_id' => config('app.tencent_cos.app_id'),
        'secret_id' => config('app.tencent_cos.secret_id'),
        'secret_key' => config('app.tencent_cos.secret_key'),
        'region' => config('app.tencent_cos.region'),   // bucket所属地域：华北 'tj' 华东 'sh' 华南 'gz'
        'timeout' => 60
    );
    date_default_timezone_set('PRC');
    $cosApi = new Api($config);
    $filename =  date('Y-m-d-H-i-s') . '-' . uniqid()  .".". $extension;
    $rs=$cosApi->upload($bucket,$url,$path.'/'.$filename);
    if ($rs['code']){
        errorLog(date('Y-m-d-H-i-s').'图片上传失败');
    }
    // 拼接处图片在云存储的地址
    $new_url = "https://onecafe-1253709024.pictj.myqcloud.com/".$path.'/'.$filename;
    // 将云存储的地址返回
    return $new_url;
}

/**
 * 从本地服务器移除图片
 * @param $url 图片在本地的绝对路径
 */
function removeImage($url)
{
    unlink($url);
}


if (! function_exists('upload_one'))
{

    function uploadPic($fileName)
    {
        $arr=getimagesize($fileName);
        if($arr['mime']=="image/png"){
            $postfix="png";
        }else{
            $postfix="jpg";
        }
        $bucket = 'onecafe';
        $config = array(
            'app_id' => config('app.tencent_cos.app_id'),
            'secret_id' => config('app.tencent_cos.secret_id'),
            'secret_key' => config('app.tencent_cos.secret_key'),
            'region' => config('app.tencent_cos.region'),   // bucket所属地域：华北 'tj' 华东 'sh' 华南 'gz'
            'timeout' => 60
        );

        date_default_timezone_set('PRC');
        $cosApi = new Api($config);
        $filename = "qrcode/" . date('Y-m-d-H-i-s') . '-' . uniqid()  .".". $postfix;
        $filenamelocal = "/usr/share/nginx/app/public/".$fileName;
        $rs=$cosApi->upload($bucket,$filenamelocal,$filename);
        $filename="http://onecafe-1253709024.pictj.myqcloud.com/".$filename;
        return $filename;
    }

    function dealHttp($url, $data = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url );
        if (!empty($data)){
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        //打印获得的数据
        $rs=json_decode($output);
        return $rs;
    }
}
function sendTemplateMsg($toUser, $templateId, $page, $formId, $data){

    $access_token=$this->getAccessToken();
    $url="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token;
    $ch = curl_init($url);
    $data = array("touser" => $toUser,"template_id"=>$templateId,"page"=>$page,"form_id"=>$formId,"data"=>$data);
    $data_string = json_encode($data);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string))
    );
    $json_data = curl_exec($ch);
    curl_close($json_data);
    $array = json_decode($json_data,true);
}
function sendSms($mobile,$content)
{
    $apikey = config('app.yunpian_sms.appkey'); //请用自己的apikey代替
    $text="【一间咖啡馆】";
    $text.=$content;
    $ch = curl_init();
    $data=array('text'=>$text,'apikey'=>$apikey,'mobile'=>$mobile);
    curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/batch_send.json');
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    $json_data = curl_exec($ch);
    //解析返回结果（json格式字符串）
    $array = json_decode($json_data,true);
    return $array;
}
function createQrcode($path,$logo="")
{
    $qrcodeName=downpicPost($path);
    $qrcode=uploadPic("$qrcodeName");
    //判断是否添加中心logo
    if($logo!=""&&$logo!="null"){
        $bool=ends_with($logo,"png");
        if($bool){
            $fileName="logo.png";
        }else{
            $fileName="logo.jpg";
        }
        $logo=$logo."?imageMogr2/crop/120x120";
        $fp_output = fopen($fileName, 'w');
        $ch = curl_init($logo);
        curl_setopt($ch, CURLOPT_FILE, $fp_output);
        curl_exec($ch);
        curl_close($ch);
        exec("libreoffice ./".$fileName, $out, $status);
        $imgg = yuan_img($fileName);
        imagepng($imgg,$fileName);
        imagedestroy($imgg);
        $name=uploadPic($fileName);
        $name=base64_encode($name);
        $qrcode=$qrcode."?watermark/1/image/".$name."/gravity/NorthEast/dx/176/dy/174";
    }
    return  $qrcode;
}
function downPicPost($path,$width="430"){
    //首先判断token是否过期
    $access_token=Redis::get('access_token');
    if(empty($access_token)){
        $access_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb980d6dc4b2c0314&secret=4e1e32a82b0e24c7570e1555f1d71fe6";
        $res=dealHttp($access_token_url);
        $access_token=$res->access_token;
        //给token赋值，并设置token生存时间3600秒
        Redis::set('access_token',$access_token);
        Redis::expire('access_token',3600);
    }
    //更新token值
    $access_token=Redis::get('access_token');

    $qrcodeUrl="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$access_token";
    $data = array("path" => $path,'width'=>$width);
    $data_string = json_encode($data);
    $ch = curl_init($qrcodeUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string))
    );
    $result = curl_exec($ch);
    //生成二维码
    $qrcodeName=date('Y-m-d-H-i-s') . '-' . uniqid().".jpg";
    file_put_contents("/usr/share/nginx/app/public/".$qrcodeName, $result);
    return $qrcodeName;
}
function downPicGet($imgUrl){
    $fileName=date('Y-m-d-H-i-s') . '-' . uniqid().".jpg";
    $fp_output = fopen($fileName, 'w');
    $ch = curl_init($imgUrl);
    curl_setopt($ch, CURLOPT_FILE, $fp_output);
    curl_exec($ch);
    curl_close($ch);
    exec("libreoffice ./".$fileName, $out, $status);
    $arr=getimagesize($fileName);
    if($arr['mime']=="image/png"){
        $fileName=date('Y-m-d-H-i-s') . '-' . uniqid().".png";
        rename($fileName,$fileName );
    }
    return $fileName;
}



//处理logo图片，变为圆形半透明
function circle_img($imgpath) {
    $ext     = pathinfo($imgpath);
    $src_img = null;
    switch ($ext['extension']) {
        case 'jpg':
            $src_img = imagecreatefromjpeg($imgpath);
            break;
        case 'png':
            $src_img = imagecreatefrompng($imgpath);
            break;
    }
    $wh  = getimagesize($imgpath);
    $w   = $wh[0];
    $h   = $wh[1];
    $w   = min($w, $h);
    $h   = $w;
    $img = imagecreatetruecolor($w, $h);
    //这一句一定要有
    imagesavealpha($img, true);
    //拾取一个完全透明的颜色,最后一个参数127为全透明
    $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
    imagefill($img, 0, 0, $bg);
    $r   = $w / 2; //圆半径
    $y_x = $r; //圆心X坐标
    $y_y = $r; //圆心Y坐标
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $rgbColor = imagecolorat($src_img, $x, $y);
            if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                imagesetpixel($img, $x, $y, $rgbColor);
            }
        }
    }

    return $img;


}

if (! function_exists('publicSendSms'))
{

    function publicSendSms($mobile,$content)
    {
        $apikey = config('app.yunpian_sms.appkey'); //请用自己的apikey代替
        $text="【一间咖啡馆】";
        $text.=$content;
        $ch = curl_init();
        $data=array('text'=>$text,'apikey'=>$apikey,'mobile'=>$mobile);
        curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/batch_send.json');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $json_data = curl_exec($ch);
        //解析返回结果（json格式字符串）
        $array = json_decode($json_data,true);

    }
}

if (! function_exists('getUserByAppUserSession'))
{

    function getUserByAppUserSession($loginSession)
    {
        $wx_app_openid=Redis::get($loginSession);
        $user = DB::table('users')->select("id")->where('wx_app_openid', $wx_app_openid)->first();
        return $user;
    }
}

if (! function_exists('return_json'))
{
    /*
     * 上传一张照片
     */
    function return_json($staus = -2,$message = "无状态", $data = "")
    {
        $arr=['staus'=>$staus,'message'=>$message,'data'=>$data];
        return $arr;
    }
}

/**
 * 通过经纬度获取详细的地址
 */
if (! function_exists('publicGetAddr'))
{
    /*
     * 上传一张照片
     */
    function publicGetAddr($latlng)
    {
        $homepage = file_get_contents('http://restapi.amap.com/v3/geocode/regeo?output=JSON&location='.$latlng.'&key=291f9ad46a4ab46cc442157ca8b573c8&radius=1000&extensions=all');
        $homepage = json_decode(($homepage));

        $regeocodes = $homepage->regeocode;         //逆地理编码列表
        $addressComponent =  $regeocodes->addressComponent;

        return $addressComponent;
    }
}
if (! function_exists('getUserId'))
{
    /*
     * 上传一张照片
     */
    function getUserId($loginSession)
    {
        $open_id=Redis::get($loginSession);
        $user_id= Users::where('wx_app_openid',$open_id)->first()->id;
        return $user_id;
    }
}

/**
 * 判断是否是微信浏览器
 * @return bool
 */
function isWechat() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    } return false;
}

/**
 * 生成指定长度的随机字符串(包含大写英文字母, 小写英文字母, 数字)
 * @param int $length 需要生成的字符串的长度
 * @return string 包含 大小写英文字母 和 数字 的随机字符串
 */
function randomStr($length)
{
    //生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
    $arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
    $str = '';
    $arr_len = count($arr);
    for ($i = 0; $i < $length; $i++)
    {
        $rand = mt_rand(0, $arr_len-1);
        $str.=$arr[$rand];
    }
    return $str;
}

/**
 * 字符串转化为数组
 * @param $str 要转化为数组的字符串
 * @param $l 每个数组元素的长度
 * @return array 返回数组
 */
function ch2arr($str, $l)
{
    $length = mb_strlen($str, 'utf-8');
    $array = [];
    for ($i=0; $i<$length; $i+=$l)
        $array[] = mb_substr($str, $i, $l, 'utf-8');
    return $array;
}

/**
 * 获取到圆形图片
 * @param string $imgpath
 * @return string
 */
function getCicleImg($imgpath = '') {
    $ext     = pathinfo($imgpath );
    errorLog($ext['extension']);
    $src_img = null;
    switch ($ext['extension']) {
        case 'jpg':
            $src_img = imagecreatefromjpeg($imgpath);
            break;
        case 'jpeg':
            $src_img = imagecreatefromjpeg($imgpath);
            break;
        case 'png':
            $src_img = imagecreatefrompng($imgpath);
            break;
        default:
            $src_img = imagecreatefrompng($imgpath);
            break;
    }
    $wh  = getimagesize($imgpath);
    $w   = $wh[0];
    $h   = $wh[1];
    $w   = min($w, $h);
    $h   = $w;
    $img = imagecreatetruecolor($w, $h);
    //这一句一定要有
    imagesavealpha($img, true);
    //拾取一个完全透明的颜色,最后一个参数127为全透明
    $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
    imagefill($img, 0, 0, $bg);
    $r   = $w /2; //圆半径
    $y_x = $r; //圆心X坐标
    $y_y = $r; //圆心Y坐标
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $rgbColor = imagecolorat($src_img, $x, $y);
            if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                imagesetpixel($img, $x, $y, $rgbColor);
            }
        }
    }
    $filename = date('Y-m-d-H-i-s').'-'.uniqid().'.png';

    imagepng($img,public_path().'/'.$filename);

    return public_path().'/'.$filename;
}

/**
 * 将返回数据中的数组转换成前端select好填充的模式
 * @param $arr
 * @return array
 */
function arrToSelect($arr)
{
    $new_arr = [];
    foreach ($arr as $key => $item){
        $item_arr = [
            'id' => $key,
            'name' => $item
        ];
        array_push($new_arr, $item_arr);
    }
    return $new_arr;
}

function doGet($url)
{
    //初始化
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,$url);
    // 执行后不直接打印出来
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    // 跳过证书检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // 不从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    //执行并获取HTML文档内容
    $output = curl_exec($ch);

    //释放curl句柄
    curl_close($ch);

    return $output;
}

/**
 * Post请求
 * @param $url
 * @param array $data
 * @return mixed
 */
function doPost($url, $data = [])
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url );
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    //打印获得的数据
    $rs=json_decode($output);
    return $rs;
}


/**
 * 将文本中的<br/>换成\n
 * @param $text
 * @return null|string|string[]
 */
function br2nl($text) {
    return preg_replace('/<br\\s*?\/??>/i', '', $text);
}